#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""feedback_api.py
反馈 API：
1) 用户提交反馈
2) 用户查看个人反馈历史
3) 管理员列表 / 过滤 / 状态流转（open -> processing -> resolved / rejected）
4) 管理员回复（记录回复与时间）
5) 状态/优先级更新

表：feedbacks （正式模型，见 Alembic 迁移）
"""
from flask import request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from datetime import datetime
from backend.api.miniprogram import miniprogram_bp
from backend.infrastructure.database import db
from backend.models.user import User
from backend.models.feedback import Feedback
from sqlalchemy import and_

# 允许的状态与流转
FEEDBACK_STATUSES = ['pending', 'processing', 'resolved', 'rejected']

@miniprogram_bp.route('/feedback', methods=['POST'])
@jwt_required()
def create_feedback():
    user_id = int(get_jwt_identity())
    data = request.get_json() or {}
    if not data.get('title') or not data.get('content'):
        return jsonify({'success': False, 'message': '标题与内容必填'}), 400
    
    user = User.query.get(user_id)
    
    # 处理图片：只接受 /media/ 开头的相对路径，过滤其它格式
    raw_images = data.get('images') or []
    if not isinstance(raw_images, list):
        return jsonify({'success': False, 'message': 'images 必须为数组'}), 400
    
    cleaned_images = []
    for img in raw_images:
        if not img or not isinstance(img, str):
            continue
        val = img.strip()
        # 已是完整 http(s) 说明前端传错，拒绝
        if val.lower().startswith('http://') or val.lower().startswith('https://'):
            print(f'feedback 拒绝绝对URL: {val}')
            return jsonify({'success': False, 'message': '图片URL必须为后端返回的相对路径'}), 400
        # 允许带多余的 /api/miniprogram/ 前缀，剥离
        if val.startswith('/api/miniprogram/'):
            val = '/' + val[len('/api/miniprogram/'):].lstrip('/')
        if not val.startswith('/'):
            val = '/' + val
        if not val.startswith('/media/'):
            print(f'feedback 跳过非媒体路径: {val}')
            continue
        cleaned_images.append(val)
    
    # 去重保持顺序
    seen = set()
    deduped_images = []
    for v in cleaned_images:
        if v not in seen:
            seen.add(v)
            deduped_images.append(v)
    
    fb = Feedback(
        user_id=user_id,
        category=data.get('type') or 'other',
        title=data.get('title').strip(),
        content=data.get('content').strip(),
        contact_info=(data.get('contact') or '').strip() or None,
        images=deduped_images,
        priority=data.get('priority') if data.get('priority') in ['low','normal','high','urgent'] else 'normal'
    )
    db.session.add(fb)
    db.session.commit()
    return jsonify({'success': True, 'data': fb.to_dict(), 'message': '提交成功'})

@miniprogram_bp.route('/feedback/history', methods=['GET'])
@jwt_required()
def feedback_history():
    user_id = int(get_jwt_identity())
    q = Feedback.query.filter(Feedback.user_id == user_id).order_by(Feedback.created_at.desc())
    return jsonify({'success': True, 'data': [i.to_dict() for i in q.limit(200).all()]})

@miniprogram_bp.route('/feedback/<int:fid>', methods=['GET'])
@jwt_required()
def get_feedback_detail(fid):
    """获取反馈详情（用户只能查看自己的反馈）"""
    user_id = int(get_jwt_identity())
    fb = Feedback.query.filter(Feedback.id == fid, Feedback.user_id == user_id).first()
    if not fb:
        return jsonify({'success': False, 'message': '记录不存在或无权访问'}), 404
    return jsonify({'success': True, 'data': fb.to_dict()})

# ===== 管理端接口（后续可迁移到单独的管理蓝图；此处先提供） =====
def _is_admin(user: User):
    # 简单判断：role 或 is_admin 字段（若存在）
    return getattr(user, 'is_admin', False) or any(r.name in ('admin','superadmin') for r in getattr(user, 'roles', []) )

@miniprogram_bp.route('/feedback/admin/list', methods=['GET'])
@jwt_required()
def admin_feedback_list():
    current_id = int(get_jwt_identity())
    user = User.query.get(current_id)
    if not user or not _is_admin(user):
        return jsonify({'success': False, 'message': '无权访问'}), 403

    status = request.args.get('status')
    ftype = request.args.get('type')
    keyword = request.args.get('keyword')
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 20, type=int)

    query = Feedback.query
    if status and status in FEEDBACK_STATUSES:
        query = query.filter(Feedback.status == status)
    if ftype:
        query = query.filter(Feedback.category == ftype)
    if keyword:
        like = f"%{keyword}%"
        query = query.filter(and_(Feedback.title.like(like) | Feedback.content.like(like)))

    query = query.order_by(Feedback.created_at.desc())
    pagination = query.paginate(page=page, per_page=per_page, error_out=False)
    return jsonify({
        'success': True,
        'data': {
            'records': [f.to_dict() for f in pagination.items],
            'pagination': {
                'page': page,
                'per_page': per_page,
                'total': pagination.total,
                'pages': pagination.pages
            }
        }
    })

@miniprogram_bp.route('/feedback/admin/<int:fid>/reply', methods=['POST'])
@jwt_required()
def admin_reply_feedback(fid):
    current_id = int(get_jwt_identity())
    user = User.query.get(current_id)
    if not user or not _is_admin(user):
        return jsonify({'success': False, 'message': '无权访问'}), 403
    fb = Feedback.query.get(fid)
    if not fb:
        return jsonify({'success': False, 'message': '记录不存在'}), 404
    data = request.get_json() or {}
    reply = (data.get('reply') or '').strip()
    if not reply:
        return jsonify({'success': False, 'message': '回复内容不能为空'}), 400
    fb.admin_reply = reply
    fb.admin_reply_at = datetime.utcnow()
    # 若仍是 pending，则自动转 processing
    if fb.status == 'pending':
        fb.status = 'processing'
    db.session.commit()
    return jsonify({'success': True, 'data': fb.to_dict()})

@miniprogram_bp.route('/feedback/admin/<int:fid>/status', methods=['PATCH'])
@jwt_required()
def admin_update_feedback_status(fid):
    current_id = int(get_jwt_identity())
    user = User.query.get(current_id)
    if not user or not _is_admin(user):
        return jsonify({'success': False, 'message': '无权访问'}), 403
    fb = Feedback.query.get(fid)
    if not fb:
        return jsonify({'success': False, 'message': '记录不存在'}), 404
    data = request.get_json() or {}
    new_status = data.get('status')
    new_priority = data.get('priority')
    changed = False
    if new_status and new_status in FEEDBACK_STATUSES:
        fb.status = new_status
        changed = True
    if new_priority and new_priority in ['low','normal','high','urgent']:
        fb.priority = new_priority
        changed = True
    if not changed:
        return jsonify({'success': False, 'message': '无有效更新字段'}), 400
    db.session.commit()
    return jsonify({'success': True, 'data': fb.to_dict()})

